package com.huika.dealontop.control.homepage.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.huika.dealontop.R;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.control.nearby.activity.MerchantDetailActivity;
import com.huika.dealontop.control.shops.activity.ProductDetailsActivity1;
import com.huika.dealontop.control.timelimit.adapter.SeachCommonAdapter;
import com.huika.dealontop.db.bean.SearchHotKey;
import com.huika.dealontop.db.dao.SearchHotDao;
import com.huika.dealontop.support.domain.SearchResultBean;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.GMapUtil;
import com.huika.dealontop.utils.PreferencesHelper;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.KeywordContainer;
import com.huika.dealontop.views.LinearLineWrapLayout;
import com.huika.huikalib.utils.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by huhao on 2015/11/25.
 */
public class SearchActivity extends BaseAct implements KeywordContainer.KeywordViewFactory, KeywordContainer
        .OnClickKeywordListener {
    public static final String SEARCHCHOOSE_ID = "searchchoose_id";
    private TextView tv_back, tv_submit;
    private EditText et_seach;
    private ArrayList<SearchResultBean> mSearchResultList = new ArrayList<SearchResultBean>();
    private String keyContent;
    private KeywordContainer kc_search;
    private ListView list_search;
    private SeachCommonAdapter seachGrouponAdapter;
    private int searchchooseID;
    private String Searchkeyjson;
    private String Searchkey;

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_search);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        final LayoutInflater inflater = LayoutInflater.from(UIUtils.getContext());
        tv_back = (TextView) findViewById(R.id.tv_left);
        Drawable leftDrawable = UIUtils.getResources().getDrawable(R.mipmap.ssdk_back_arr);
        leftDrawable.setBounds(0, 0, UIUtils.dip2px(19), UIUtils.dip2px(20));
        tv_back.setCompoundDrawables(leftDrawable, null, null, null);
        tv_submit = (TextView) findViewById(R.id.tv_right);
        et_seach = (EditText) findViewById(R.id.et_searchs);
        kc_search = (KeywordContainer) findViewById(R.id.kc_search_tags);
        kc_search.setKeywordViewFactory(this);
        kc_search.setOnClickKeywordListener(this);
        list_search = (ListView) findViewById(R.id.lv_search_list);
        tv_back.setOnClickListener(this);
        tv_submit.setOnClickListener(this);
        seachGrouponAdapter = new SeachCommonAdapter(this);
        seachGrouponAdapter.setType(searchchooseID);
        list_search.setAdapter(seachGrouponAdapter);
        et_seach.setFocusable(true);
        et_seach.setFocusableInTouchMode(true);
        et_seach.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) et_seach.getContext().getSystemService(Context
                                               .INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(et_seach, 0);
                           }

                       },
                998);
        if (searchchooseID == 0) {
            getHistoryProduct();
            et_seach.setHint(R.string.search_content);
        } else {
            getHistoryBusiness();
            et_seach.setHint(R.string.nearby_titleright);
        }

                list_search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                if (seachGrouponAdapter.getItem(position).getType() == 2) {
                    //跳至团购商品详情
                    String mProductID = seachGrouponAdapter.getItem(position).getCouMerID();
                    Intent intent = new Intent(UIUtils.getContext(), ProductDetailsActivity1.class);
                    intent.putExtra(ProductDetailsActivity1.PRODUCT_ID, mProductID);
                    intent.putExtra(ProductDetailsActivity1.PRODUCT_IMG, seachGrouponAdapter.getItem(position)
                            .getCouMerImage());
                    showActivity(SearchActivity.this, intent);
                } else if (seachGrouponAdapter.getItem(position).getType() == 1) {
                    //跳至商家详情
                    String mCouMerID = seachGrouponAdapter.getItem(position).getCouMerID();
                    Bundle bundle = new Bundle();
                    bundle.putString(MerchantDetailActivity.Merchant_ID, mCouMerID);
                    showActivity(SearchActivity.this, MerchantDetailActivity.class, bundle);
                }
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();
        if (intent != null) {
            searchchooseID = intent.getIntExtra(SEARCHCHOOSE_ID, -1);
        }
    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            case R.id.tv_left:
                finish();
                break;
            case R.id.tv_right:
                //提交关键词进行搜索商家或商品
                keyContent = getInputStr(et_seach);
                if (!StringUtils.isEmpty(keyContent)) {
                    getUserEvaluationList(keyContent);
                } else {
                    showToastMsg(getString(R.string.search_emptycontent));
                }
                break;
        }
    }

    /**
     * 搜索关键词联网查询
     */
    private void getUserEvaluationList(String keyContent) {
        double x = 0;
        double y = 0;
        if (new GMapUtil().getCurrentLat().equals("") || StringUtils.isEmpty(new GMapUtil().getCurrentLat()) || new
                GMapUtil().getCurrentLng().equals("") || StringUtils.isEmpty(new GMapUtil().getCurrentLng())) {
            x = 0.000000;
            y = 0.000000;
        } else {
            y = Double.valueOf(new GMapUtil().getCurrentLat());
            x = Double.valueOf(new GMapUtil().getCurrentLng());
        }
        showLoadingDialog("");
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("couMerName", keyContent);
        ajaxParams.putCommonTypeParam("longitudeX", x);//经度
        ajaxParams.putCommonTypeParam("dimensionsY", y);//维度
        FormResultRequest<ArrayList<SearchResultBean>> request = new FormResultRequest<ArrayList<SearchResultBean>>
                (UrlConstants
                        .SEARCHCONTENT, mSearchResult, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        dismissLoadingDialog();
                        kc_search.setVisibility(View.GONE);
                        if (searchchooseID == 0) {
                            showEmptyLayView(list_search, R.string.search_empty, R.mipmap.emptyseach);
                        } else if (searchchooseID == 1) {
                            showEmptyLayView(list_search, R.string.Merchant_emptyshangjia, R.mipmap.emptyseach);
                        } else {
                            showEmptyLayView(list_search, R.string.Merchant_emptytuangou, R.mipmap.emptyseach);
                        }
                    }
                }, new
                        TypeToken<RequestResult<ArrayList<SearchResultBean>>>
                                () {
                        }.getType());
        request.setRequestParams(ajaxParams);
//        seachGrouponAdapter.clearGroup(true);
        executeRequest(request);
    }

    private Response.Listener<RequestResult<ArrayList<SearchResultBean>>> mSearchResult = new
            Response.Listener<RequestResult<ArrayList<SearchResultBean>>>() {
                @Override
                public void onResponse(RequestResult<ArrayList<SearchResultBean>> Result) {
                    dismissLoadingDialog();
                    if (Result.flag == 1) {
                        hideEmptyLayView();
                        kc_search.setVisibility(View.GONE);
                        list_search.setVisibility(View.VISIBLE);
                        mSearchResultList = Result.getRs();
                        seachGrouponAdapter.setGroup(mSearchResultList);
                    }

                    boolean falg = true;
                    for (int i = 0; i < mSearchResultList.size(); i++) {
                        if (searchchooseID == 1 && mSearchResultList.get(i).getType() == 1) {
                            falg = false;
                        } else if (searchchooseID == 0) {
                            falg = false;
                        }
                    }

                    if (!falg) {
                        if (searchchooseID == 1) {
                            saveToHistoryBusiness(keyContent);
                        } else {
                            saveToHistoryProduct(keyContent);
                        }
                    }

                    if (falg && searchchooseID == 1) {
                        showEmptyLayView(list_search, R.string.Merchant_emptyshangjia, R.mipmap.emptyseach);
                    } else if (falg && searchchooseID == 0) {
                        showEmptyLayView(list_search, R.string.search_empty, R.mipmap.emptyseach);
                    }

                    kc_search.setVisibility(View.GONE);
                }
            };

    /**
     * 保存到历史记录
     */
    private void saveToHistoryProduct(String key) {
//        List<String> list = new ArrayList<>();
//        //先拿出历史的字符串
//        String history = PreferencesHelper.getString("seachproductkey");
//        if (!TextUtils.isEmpty(history)) {
//            //将历史字符串拆分 数组
//            String arr[] = history.split("#");
//            for (String t : arr) {
//                list.add(t);
//            }
//        }
//        //检查历史记录是否有该标签有就去除
//        list.remove(key);
//        // 在添加到最顶
//        list.add(0, key);
//        if (list.size() >= 7) {
//            list.remove(list.size() - 1);
//        }
//        //将list 拼成字符串在保存到缓存
//        StringBuilder sb = new StringBuilder();
//        for (int i = 0; i < list.size(); i++) {
//            sb.append(list.get(i));
//            if (i < list.size() - 1) {
//                sb.append("#");
//            }
//        }
//
//        PreferencesHelper.setString("seachproductkey", sb.toString());
//        String[] arr = new String[list.size()];
//
//        list.toArray(arr);//ndk jni
        addKey(key);
        kc_search.setKeywords(getHotKeyArray());
    }

    private String[] getHotKeyArray(){
        List<SearchHotKey> list = getHotKeyList();
        String[] array = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            array[i] = list.get(i).getKey();
        }
        return array;
    }

    private List<SearchHotKey> getHotKeyList(){
        return getDAO().getTOP6();
    }

    private void addKey(String key){
        //先查询是否有
        SearchHotKey result = getDAO().query(key);
        if(result == null){
            //如果没有就走 add
            result = new SearchHotKey();
            result.setKey(key);
            result.setCount(1);
            getDAO().add(result);
        }else{
            //如果有就走 update
            result.setCount(result.getCount() + 1);
            getDAO().update(result);
        }
    }




    private SearchHotDao dao;
    private SearchHotDao getDAO(){
        if(dao == null){
            dao = new SearchHotDao(this);
        }
        return dao;
    }

    private void getHistoryProduct() {
        /*//先拿出历史的字符串
        String history = PreferencesHelper.getString("seachproductkey");
        if (!TextUtils.isEmpty(history)) {
            //将历史字符串拆分 数组
            String arr[] = history.split("#");
            kc_search.setKeywords(arr);
        }*/
        kc_search.setKeywords(getHotKeyArray());
    }

    public void getLatestCityAddress(String key) {
        if (StringUtils.isEmpty(key)) {
            return;
        }
        if (StringUtils.isEmpty(Searchkeyjson)) {
            Searchkey = key + "#1";
            Searchkeyjson = Searchkey;
            PreferencesHelper.getInstance().setString("seachproductkey", Searchkey);
            CommonCity();
            return;
        }
        String[] arycitys = Searchkeyjson.split("##");
        for (int i = 0; i < arycitys.length; i++) {
            if (arycitys[i].split("").equals(key)) {
                Searchkeyjson = key + "#1##" + Searchkeyjson;
                PreferencesHelper.getInstance().setString("seachproductkey", Searchkeyjson);
                CommonCity();
                return;
            }
        }
        List list = Arrays.asList(arycitys);
        if (list.size() >= 6) {
            list.remove(list.size() - 1);
        }
        for (int i = 0; i < arycitys.length; i++) {
            if (arycitys[i].split("#")[0].equals(key)) {
                key = key + "#" + (Integer.parseInt(arycitys[i].split("#")[1]) + 1);
            }
        }
        StringBuffer sb = new StringBuffer();
        sb.append(key);
        for (int i = 0; i < arycitys.length; i++) {
            if (!key.split("#")[0].equals(arycitys[i].split("#")[0])) {
                sb.append("##" + arycitys[i]);
            }
        }
        Searchkeyjson = sb.toString();
        PreferencesHelper.getInstance().setString("seachproductkey", Searchkeyjson);
        CommonCity();
    }

    private void CommonCity() {
        Searchkeyjson = PreferencesHelper.getString("seachproductkey");
        if (!StringUtils.isEmpty(Searchkeyjson)) {
            String[] arycity = Searchkeyjson.split("##");
            Searchkey = arycity[0];
            for (int i = 0; i < arycity.length; i++) {
                if (Integer.parseInt(Searchkey.split("#")[1]) < Integer.parseInt(arycity[i].split("#")[1])) {
                    Searchkey = arycity[i];
                }
            }
            kc_search.setKeywords(Searchkey.split("#")[0]);
        }
    }

    /**
     * 保存到历史记录
     */
    private void saveToHistoryBusiness(String key) {
//        List<String> list = new ArrayList<>();
//        //先拿出历史的字符串
//        String history = PreferencesHelper.getString("seachbusinesskey");
//        if (!TextUtils.isEmpty(history)) {
//            //将历史字符串拆分 数组
//            String arr[] = history.split("#");
//            for (String t : arr) {
//                list.add(t);
//            }
//        }
//        //检查历史记录是否有该标签有就去除
//        list.remove(key);
//        // 在添加到最顶
//        list.add(0, key);
//        if (list.size() >= 7) {
//            list.remove(list.size() - 1);
//        }
//        //将list 拼成字符串在保存到缓存
//        StringBuilder sb = new StringBuilder();
//        for (int i = 0; i < list.size(); i++) {
//            sb.append(list.get(i));
//            if (i < list.size() - 1) {
//                sb.append("#");
//            }
//        }
//
//        PreferencesHelper.setString("seachbusinesskey", sb.toString());
//        String[] arr = new String[list.size()];
//
//        list.toArray(arr);//ndk jni
//
//        kc_search.setKeywords(arr);
        addKey(key);
        kc_search.setKeywords(getHotKeyArray());
    }

    private void getHistoryBusiness() {
//        //先拿出历史的字符串
//        String history = PreferencesHelper.getString("seachbusinesskey");
//        if (!TextUtils.isEmpty(history)) {
//            //将历史字符串拆分 数组
//            String arr[] = history.split("#");
//            kc_search.setKeywords(arr);
//        }
        kc_search.setKeywords(getHotKeyArray());
    }


    @Override
    public TextView makeKeywordView(int position, String text) {
        TextView tv = new TextView(UIUtils.getContext());
        tv.setGravity(Gravity.CENTER);
        tv.setTextColor(UIUtils.getColor(R.color.color_777777));
        tv.setTextSize(UIUtils.dip2px(12));
        tv.setPadding(UIUtils.dip2px(10), UIUtils.dip2px(5), UIUtils.dip2px(10), UIUtils.dip2px(5));
        LinearLineWrapLayout.LayoutParams params = new LinearLineWrapLayout.LayoutParams(LinearLineWrapLayout
                .LayoutParams.WRAP_CONTENT, LinearLineWrapLayout
                .LayoutParams.WRAP_CONTENT);
        params.leftMargin = UIUtils.dip2px(5);
        params.rightMargin = UIUtils.dip2px(5);
        params.bottomMargin = UIUtils.dip2px(10);
        tv.setLayoutParams(params);
        tv.setBackgroundResource(R.drawable.round_corner_white);
        return tv;
    }

    @Override
    public void onClickKeyword(int position, String key) {
        keyContent = key;
        getUserEvaluationList(key);
    }
}
